package com.freedom.shiro.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;


/**
 * 不使用自定义过滤器（弃用）
 * @author HGJ
 */
 
public class ResourceCheckFilter extends AccessControlFilter {
	static final String LOGIN_URL = "http://127.0.0.1:8089/applyshrio/w/login";
	static final String UNAUTHORIZED_URL = "http://127.0.0.1:8089/applyshrio/w/error";

	/**
	 * 否允许访问，返回 true 表示允许
	 */
	 
	@Override
	protected boolean isAccessAllowed(ServletRequest request,
			ServletResponse response, Object mappedValue) throws Exception {
		Subject subject = getSubject(request, response);
		//String url = WebUtils.getPathWithinApplication(request);
		String url = getPathWithinApplication(request);
		System.out.println("请求地址："+url);
		return subject.isPermitted(url);
	}

	/**
	 * 访问拒绝也处理
	 */
	 
	@Override
	protected boolean onAccessDenied(ServletRequest request,
			ServletResponse response) throws Exception {
		Subject subject = getSubject(request, response);  
        if (subject.getPrincipal() == null) {//表示没有登录，重定向到登录页面  
            saveRequest(request);  
            WebUtils.issueRedirect(request, response, LOGIN_URL);  
        } else {  
            if (StringUtils.hasText(UNAUTHORIZED_URL)) {//如果有未授权页面跳转过去  
                WebUtils.issueRedirect(request, response, UNAUTHORIZED_URL);  
            } else {//否则返回401未授权状态码  
                WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);  
            }  
        }  
		return false;
	}

}